package com.bwie.common.utils;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class HttpRequestUtils {

    // 私有构造函数防止实例化
    private HttpRequestUtils() {
    }

    /**
     * 获取当前请求的 HttpServletRequest 对象
     */
    public static HttpServletRequest getCurrentRequest() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (servletRequestAttributes != null) {
            return servletRequestAttributes.getRequest();
        }
        throw new IllegalStateException("当前不在 HTTP 请求上下文中");
    }

    /**
     * 从当前请求中获取指定的 header 值
     */
    public static String getHeader(String name) {
        HttpServletRequest request = getCurrentRequest();
        return request.getHeader(name);
    }

    /**
     * 获取客户端 IP 地址
     */
    public static String getClientIp() {
        HttpServletRequest request = getCurrentRequest();
        String ip = request.getHeader("X-FORWARDED-FOR");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    // 可以根据需要添加更多方法
}